package com.ruoyi.organization.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.img.FontUtil;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.ruoyi.business.domain.BizCoupon;
import com.ruoyi.business.domain.BoardViewVo;
import com.ruoyi.business.domain.vo.FamilyDto;
import com.ruoyi.business.service.IBizCouponService;
import com.ruoyi.business.service.IBizPeopleCouponService;
import com.ruoyi.business.service.IBizPeopleGoodsService;
import com.ruoyi.business.service.IBizSellerService;
import com.ruoyi.common.annotation.CommunityScope;
import com.ruoyi.common.config.WxServiceProperties;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.BizCommunity;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.GirdSetting;
import com.ruoyi.common.enums.Whether;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.organization.domain.BizFamily;
import com.ruoyi.organization.domain.BizGrid;
import com.ruoyi.organization.domain.BizGridMapping;
import com.ruoyi.organization.domain.BizPeople;
import com.ruoyi.organization.domain.vo.*;
import com.ruoyi.organization.mapper.BizPeopleMapper;
import com.ruoyi.organization.service.*;
import com.ruoyi.system.domain.vo.ExtraConfig;
import com.ruoyi.system.service.ISysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.imaging.PixelDensity;
import org.apache.commons.imaging.formats.tiff.TiffImageParser;
import org.apache.commons.imaging.formats.tiff.TiffImagingParameters;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.w3c.dom.Element;

import javax.annotation.Resource;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 村民Service业务层处理
 *
 * @author ruoyi
 * @date 2024-05-10
 */
@Slf4j
@Service
public class BizPeopleServiceImpl implements IBizPeopleService {

    @Resource
    private BizPeopleMapper bizPeopleMapper;

    @Resource
    private IBizGridService gridService;

    @Resource
    private IBizCommunityService bizCommunityService;

    @Resource
    private ISysConfigService sysConfigService;

    @Autowired
    private IBizGridMappingService gridMappingService;

    @Autowired
    private IBizFamilyScoreLogService bizFamilyScoreLogService;
    @Autowired
    private IBizSellerService bizSellerService;

    @Autowired
    private IBizCouponService bizCouponService;

    @Autowired
    private IBizPeopleGoodsService bizPeopleGoodsService;

    @Autowired
    private IBizPeopleCouponService bizPeopleCouponService;

    @Autowired
    private IBizFamilyService familyService;
	@Autowired
	private BizFamilyServiceImpl bizFamilyServiceImpl;

    /**
     * 查询村民
     *
     * @param peopleId 村民主键
     * @return 村民
     */
    @Override
    public BizPeople selectBizPeopleByPeopleId(Long peopleId) {
        return bizPeopleMapper.selectBizPeopleByPeopleId(peopleId);
    }

    /**
     * 查询村民列表
     *
     * @param bizPeople 村民
     * @return 村民
     */
    @Override
    @CommunityScope(alias = "")
    public List<BizPeople> selectBizPeopleList(BizPeople bizPeople) {
        if(Objects.nonNull(bizPeople.getStatus()) && bizPeople.getStatus() == 4) {
            bizPeople.setStatus(1);
            bizPeople.setOpenId("2");
        }
        List<BizPeople> peopleList = bizPeopleMapper.selectBizPeopleList(bizPeople);
        return peopleList;
    }


    @Override
    public Map<String, BizPeople> selectBizPeopleMap(BizPeople bizPeople) {
        List<BizPeople> peopleList = bizPeopleMapper.selectBizPeopleList(bizPeople);
        if (CollUtil.isEmpty(peopleList)) {
            return new HashMap<>();
        }
        return peopleList.stream().collect(HashMap::new, (m, v) -> m.put(v.getPeopleCard(), v), HashMap::putAll);
    }


    /**
     * 居民列表的网格
     *
     * @param dataTable
     * @return
     */
    @Override
    public TableDataInfo doPeopleGird(TableDataInfo dataTable) {
        Long total = dataTable.getTotal();
        List<BizPeopleListVo> ss = new ArrayList<>();
        List<BizPeople> rows = (List<BizPeople>) dataTable.getRows();
        for (BizPeople people : rows) {
            people.setPeopleCard(BizUtils.maskIdCard(people.getPeopleCard()));
            people.setHeadCard(BizUtils.maskIdCard(people.getHeadCard()));
            people.setPeopleMobile(BizUtils.maskPhoneNumber(people.getPeopleMobile()));
            BizPeopleListVo s = new BizPeopleListVo();
            BeanUtils.copyProperties(people, s);
            if (people.getIsGrid().equals(1L)) {
                BizGridMapping mapping = new BizGridMapping();
                mapping.setPeopleId(people.getPeopleId());
                List<BizGridMapping> bizGridMappings = gridMappingService.selectBizGridMappingList(mapping);
                Map<String, List<BizGridMapping>> gridMappingMap = bizGridMappings.stream()
                        .collect(Collectors.groupingBy(BizGridMapping::getCommunityName));
                String setting = "";
                for (Map.Entry<String, List<BizGridMapping>> entry : gridMappingMap.entrySet()) {
                    setting = setting + entry.getKey() + ":";
                    for (BizGridMapping bizGridMapping : entry.getValue()) {
                        setting = setting + bizGridMapping.getGridName() + ",";
                    }
                }
                if (StringUtils.isNotEmpty(setting)) {
                    s.setGridString(setting.substring(0, setting.length() - 1));
                }
            }
            ss.add(s);
        }
        TableDataInfo tableDataInfo = new TableDataInfo(ss, Integer.valueOf(total.toString()));
        return tableDataInfo;
    }

    /**
     * 设置党员
     *
     * @param bizPeople
     * @return
     */
    @Override
    public int changeIsParty(BizPeople bizPeople) {
        BizPeople find = this.bizPeopleMapper.selectBizPeopleByPeopleId(bizPeople.getPeopleId());
        if (ObjectUtil.isNull(find)) {
            throw new ServiceException("该居民不存在");
        }
        find.setIsParty(bizPeople.getIsParty());
        find.setUpdateBy(SecurityUtils.getUsername());
        find.setUpdateTime(DateUtil.date());
        return this.bizPeopleMapper.updateBizPeople(find);
    }

    /**
     * 导入网格员
     *
     * @param userList
     * @param updateSupport
     * @param operName
     * @return
     */
    @Override
    public String importGridData(List<BizBridVo> userList, boolean updateSupport, String operName) {
        if (userList.size() == 0) {
            throw new ServiceException("请补全数据再进行上传");
        }
        //先处理数据
        List<BizBridVo> newBizBrids = new ArrayList<>();
        List<InnerBizBrid> innerBizBrids = new ArrayList<>();
        for (BizBridVo bizBridVo : userList) {
            BizBridVo newBizBrid = new BizBridVo();
            InnerBizBrid innerBizBrid = new InnerBizBrid();
            newBizBrid.setPeopleName(BizUtils.cleanString(bizBridVo.getPeopleName()));
            newBizBrid.setPeopleMobile(BizUtils.cleanString(bizBridVo.getPeopleMobile()));
            newBizBrid.setCommunity(BizUtils.cleanString(bizBridVo.getCommunity()));
            newBizBrid.setGridName(BizUtils.cleanString(bizBridVo.getGridName()));
            innerBizBrid.setPeopleMobile(newBizBrid.getPeopleMobile());
            innerBizBrid.setPeopleName(newBizBrid.getPeopleName());
            innerBizBrids.add(innerBizBrid);
            newBizBrids.add(newBizBrid);
        }
        this.checkGridDataEmpty(newBizBrids);
        //查询要设置的网格员
        List<BizPeople> bizPeoples = this.findAllGridByMobileAndName(innerBizBrids);
        if (bizPeoples.size() == 0) {
            throw new ServiceException("没有找到指定的网格员");
        }
        //todo 社区
        List<BizCommunity> communities = bizCommunityService.selectBizCommunityListFromNoScope(new BizCommunity());
        List<BizGrid> bizGrids = gridService.selectBizGridListNoScope(new BizGrid());
        Map<String, BizCommunity> communitiesMap = communities.stream().collect(Collectors.toMap(BizCommunity::getCommunityName, BizCommunity -> BizCommunity));
        Map<Long, List<BizGrid>> bizGridsMap = bizGrids.stream().collect(Collectors.groupingBy(BizGrid::getCommunityId));
        //设置网格
        int i = 0;
        for (BizBridVo newBizBrid : newBizBrids) {

            for (BizPeople bizPeople : bizPeoples) {
                if (!bizPeople.getPeopleName().equals(newBizBrid.getPeopleName())
                        || !bizPeople.getPeopleMobile().equals(newBizBrid.getPeopleMobile())) {
                    continue;
                }
                //匹配网格
                String[] split = newBizBrid.getGridName().split(",");
                //先确定社区 再看社区下面的网格
                BizCommunity bizCommunity = communitiesMap.get(newBizBrid.getCommunity());
                List<BizGrid> grid = bizGridsMap.get(bizCommunity.getCommunityId());
                List<GirdVo.InnerGirds> inners = new ArrayList<>();
                for (String s : split) {
                    BizGrid bizGrid = grid.stream().filter(g -> g.getGridName().equals(s)).findFirst().orElse(null);
                    if (ObjectUtil.isNull(bizGrid)) {
                        continue;
                    }
                    GirdVo.InnerGirds innerGirds = new GirdVo.InnerGirds();
                    innerGirds.setId(bizGrid.getGridId());
                    innerGirds.setLabel(bizGrid.getGridName());
                    inners.add(innerGirds);
                }
                GirdVo gridVo = new GirdVo();
                gridVo.setPeopleId(bizPeople.getPeopleId());
                gridVo.setIsSetting(1);
                gridVo.setGirds(inners);
                gridVo.setCommunityId(bizCommunity.getCommunityId());
                gridVo.setCommunityName(bizCommunity.getCommunityName());
                this.setGird(gridVo);
                i++;
            }
        }
        return "导入" + i + "网格员信息";
    }

    /**
     * 查询指定的人
     *
     * @param innerBizBrids
     * @return
     */
    @Override
    public List<BizPeople> findAllGridByMobileAndName(List<InnerBizBrid> innerBizBrids) {
        List<BizPeople> peoples = new ArrayList<>();
        for (InnerBizBrid innerBizBrid : innerBizBrids) {
            BizPeople bizPeople = this.bizPeopleMapper.selectBizPeopleByNameAndMobile(innerBizBrid.getPeopleName()
                    , innerBizBrid.getPeopleMobile());
            peoples.add(bizPeople);
        }
        return peoples;
    }

    /**
     * 设置用户迁入
     *
     * @param ingoing
     * @return
     */
    @Override
    public int setIngoing(Ingoing ingoing, String opName) {
        if (ObjectUtil.isNull(ingoing) || ObjectUtil.isNull(ingoing.getPeopleId()) || ObjectUtil.isNull(ingoing.getNewPeopleId())) {
            throw new ServiceException("参数错误");
        }

        //查询当前用户下是否有家庭成员
        BizPeople bizPeople = this.bizPeopleMapper.selectBizPeopleByPeopleId(ingoing.getPeopleId());
        BizPeople newFamily = this.bizPeopleMapper.selectBizPeopleByPeopleId(ingoing.getNewPeopleId());
        if (Objects.isNull(bizPeople)) {
            throw new ServiceException("当前要迁入的居民不存在");
        }
        if (Objects.isNull(newFamily)) {
            throw new ServiceException("迁入的家庭数据不存在");
        }
        //查询当前要迁出的家庭是否是党员家庭
        BizPeople isParty = this.bizPeopleMapper.findIsParty(bizPeople.getHeadCard());
        if (Objects.nonNull(isParty)) {
            throw new ServiceException("当前要迁入的居民是党员家庭,不能进行迁移操作");
        }
        if (bizPeople.getHeadCard().equals(newFamily.getHeadCard())) {
            throw new ServiceException("当前要迁入的居民与要迁入的家庭已经是同户主了");
        }
        //查看要迁入的家庭成员
        BizPeople in = new BizPeople();
        in.setHeadCard(bizPeople.getHeadCard());
        List<BizPeople> inFamily = this.bizPeopleMapper.familyPeople(in);
        if (Objects.nonNull(inFamily) && (inFamily.size() > 1 && bizPeople.getIsHead().equals(1l))) {
            throw new ServiceException("当前要迁入的居民存在家庭成员,请先将其他成员设置成户主");
        }

        if (!newFamily.getIsHead().equals(1l)) {
            throw new ServiceException("当前要迁入的家庭户主信息有误");
        }
        bizPeople.setIsHead(0l);
        bizPeople.setHeadCard(newFamily.getHeadCard());
        bizPeople.setUpdateTime(DateUtils.getNowDate());
        bizPeople.setUpdateBy(opName);
        return this.bizPeopleMapper.updateBizPeople(bizPeople);
    }

    private void checkGridDataEmpty(List<BizBridVo> newBizBrids) {
        int row = 2;
        for (BizBridVo newBizBrid : newBizBrids) {
            if (StringUtils.isEmpty(newBizBrid.getPeopleName())) {
                throw new ServiceException("表格第" + row + "行,网格员->姓名空了");
            } else if (StringUtils.isEmpty(newBizBrid.getPeopleMobile())) {
                throw new ServiceException("表格第" + row + "行,网格员->手机号码空了");
            } else if (StringUtils.isEmpty(newBizBrid.getGridName())) {
                throw new ServiceException("表格第" + row + "行,网格员->身份证空了");
            } else if (StringUtils.isEmpty(newBizBrid.getCommunity())) {
                throw new ServiceException("表格第" + row + "行,网格员->运营村社空了");
            }
            row++;
        }
    }

    private void checkValid(BizPeople bizPeople) {
        //todo 校验当前新增的用户是否存在
        if (!IDCardUtil.isValid(bizPeople.getPeopleCard())) {
            throw new ServiceException("请输入正确的身份证号");
        }
        if (!Validator.isMobile(bizPeople.getPeopleMobile())) {
            throw new ServiceException("请输入正确的手机号");
        }
        if (Objects.isNull(bizPeople.getPeopleId())) {
            //居民身份证
            BizPeople exist = this.bizPeopleMapper.findByPeopleCard(bizPeople.getPeopleCard());
            if (Objects.nonNull(exist)) {
                throw new ServiceException("当前身份证号已经存在");
            }
            //新增的是户主则需要检查当前户主身份证是否已经存在
            if (bizPeople.getIsHead().equals(1L)) {
                BizPeople headCard = this.bizPeopleMapper.findByHeadCard(bizPeople.getHeadCard());
                if (Objects.nonNull(headCard)) {
                    throw new ServiceException("当前户主身份证号已经存在");
                }
                bizPeople.setHeadCard(bizPeople.getHeadCard());
            }
            BizPeople p = this.bizPeopleMapper.findByMobile(bizPeople.getPeopleMobile());
            if (Objects.nonNull(p)) {
                throw new ServiceException("当前手机号已经存在");
            }
        }
        //更新
        else {
            BizPeople exist = this.bizPeopleMapper.findByPeopleCard(bizPeople.getPeopleCard());
            if (Objects.nonNull(exist) && !exist.getPeopleId().equals(bizPeople.getPeopleId())) {
                throw new ServiceException("当前修改的身份证号已经存在");
            }
            BizPeople p = this.bizPeopleMapper.findByMobile(bizPeople.getPeopleMobile());
            if (Objects.nonNull(p) && !p.getPeopleId().equals(bizPeople.getPeopleId())) {
                throw new ServiceException("当前修改的手机号码已经存在");
            }
        }
    }

    /**
     * 新增村民
     *
     * @param bizPeople 村民
     * @return 结果
     */
    @Override
    public int insertBizPeople(BizPeople bizPeople) {
        if (ObjectUtil.isNotNull(bizPeople.getHeadPeopleId())) {
            BizPeople headPeople = bizPeopleMapper.selectBizPeopleByPeopleId(bizPeople.getHeadPeopleId());
            if (ObjectUtil.isNotNull(headPeople)) {
                bizPeople.setHeadCard(headPeople.getPeopleCard());
            }
        }
        bizPeople.setCreateTime(DateUtils.getNowDate());
        this.checkValid(bizPeople);
        //是户主
        if (bizPeople.getIsHead().equals(1L)) {
            bizPeople.setHeadCard(bizPeople.getHeadCard());
            bizPeople.setIsHead(1L);
        }
        bizPeople.setUpdateTime(DateUtils.getNowDate());
        bizPeople.setPeopleBirth(IDCardUtil.getBirthday(bizPeople.getPeopleCard()));
        bizPeople.setPeopleSex(IDCardUtil.getSex(bizPeople.getPeopleCard()));
        bizPeople.setStatus(1);
        if (bizPeople.getIsHead().equals(1L)) {
            ExtraConfig specialConfigValue = sysConfigService.getSpecialConfigValue();
            BizFamily bizFamily = new BizFamily();
            bizFamily.setCommunityId(bizPeople.getCommunityId());
            bizFamily.setCommunityName(bizPeople.getCommunityName());
            bizFamily.setFamilyHeadCard(BizUtils.cleanString(bizPeople.getHeadCard()));
            bizFamily.setFamilyMobile(bizPeople.getPeopleMobile());
            bizFamily.setFamilyName(bizPeople.getPeopleName());
            bizFamily.setFamilyScore(0L);
            bizFamily.setExpireStart(DateUtils.str2localDate(specialConfigValue.getStart()));
            bizFamily.setExpireEnd(DateUtils.str2localDate(specialConfigValue.getEnd()));
            familyService.insertBizFamily(bizFamily);
        }
        return bizPeopleMapper.insertBizPeople(bizPeople);
    }

    /**
     * 修改村民
     *
     * @param bizPeople 村民
     * @return 结果
     */
    @Override
    public int updateBizPeople(BizPeople bizPeople) {
        //todo检查户主是否已经存在
        this.checkValid(bizPeople);
        bizPeople.setUpdateTime(DateUtils.getNowDate());
        bizPeople.setPeopleBirth(IDCardUtil.getBirthday(bizPeople.getPeopleCard()));
        bizPeople.setPeopleSex(IDCardUtil.getSex(bizPeople.getPeopleCard()));
        return bizPeopleMapper.updateBizPeople(bizPeople);
    }

    /**
     * 批量删除村民
     *
     * @param peopleIds 需要删除的村民主键
     * @return 结果
     */
    @Override
    public int deleteBizPeopleByPeopleIds(Long[] peopleIds) {
        return bizPeopleMapper.deleteBizPeopleByPeopleIds(peopleIds);
    }

    /**
     * 删除村民信息
     *
     * @param peopleId 村民主键
     * @return 结果
     */
    @Override
    public int deleteBizPeopleByPeopleId(Long peopleId) {
        return bizPeopleMapper.deleteBizPeopleByPeopleId(peopleId);
    }

    /**
     * 导入用户
     *
     * @param userList
     * @param updateSupport
     * @param operName
     * @return
     */
    @Override
    public String importUser(List<BizPeopleVo> userList, boolean updateSupport, String operName) {
        if (userList.size() == 0) {
            throw new ServiceException("请补全数据再进行上传");
        }
        //户主身份证
        List<String> headCards = userList.stream()
                .filter(h -> StringUtils.isNotEmpty(BizUtils.cleanString(h.getPeopleCard())))
                .map(BizPeopleVo::getPeopleCard)
                .distinct()
                .collect(Collectors.toList());
        List<String> headCard = new ArrayList<String>();
        for (String s : headCards) {
            headCard.add(BizUtils.cleanString(s));
        }
        int row = 2;
        //检查上传的表格是否有空
        for (BizPeopleVo bizPeopleVo : userList) {
            this.doEmpty(bizPeopleVo, row);
            row++;
        }
        row = 2;
        //已经存在的户主身份证
        List<BizPeople> existCards = this.bizPeopleMapper.getListByCards(headCard);
        Map<String, String> existCardMap = existCards.stream().collect(Collectors.toMap(BizPeople::getPeopleCard, BizPeople::getPeopleName));
        if (existCards.size() > 0) {
            List<String> st = new ArrayList<>();
            for (BizPeopleVo bizPeopleVo : userList) {
                if (existCardMap.containsKey(BizUtils.cleanString(bizPeopleVo.getPeopleCard()))) {
                    st.add(BizUtils.cleanString(bizPeopleVo.getPeopleCard()));
                }
            }
        }
        List<String> error = new ArrayList<>();
        //todo 社区
        List<BizCommunity> communities = bizCommunityService.selectBizCommunityList(new BizCommunity());
        List<BizGrid> bizGrids = gridService.selectBizGridList(new BizGrid());
        Map<String, BizCommunity> communitiesMap = communities.stream().collect(Collectors.toMap(BizCommunity::getCommunityName, BizCommunity -> BizCommunity));
        Map<Long, List<BizGrid>> bizGridsMap = bizGrids.stream().collect(Collectors.groupingBy(BizGrid::getCommunityId));

        //查询当前表格内的村民是否已经存在
        int i = 0;
        ExtraConfig specialConfigValue = sysConfigService.getSpecialConfigValue();
        for (BizPeopleVo bizPeopleVo : userList) {
            if (existCardMap.containsKey(BizUtils.cleanString(bizPeopleVo.getPeopleCard()))) {
                continue;
            }
            BizPeople bizPeople = new BizPeople();
            bizPeople.setCreateBy(operName);
            bizPeople.setCreateTime(DateUtils.getNowDate());
            bizPeople.setPeopleName(bizPeopleVo.getPeopleName());
            bizPeople.setPeopleMobile(bizPeopleVo.getPeopleMobile());
            bizPeople.setHeadCard(BizUtils.cleanString(bizPeopleVo.getHeadPeopleCard()));
            bizPeople.setPeopleCard((BizUtils.cleanString(bizPeopleVo.getPeopleCard())));
            this.doCommunity(communitiesMap, bizPeopleVo, bizPeople);
            this.doGrids(bizGridsMap, bizPeopleVo, bizPeople);
            this.doIsGrid(bizPeopleVo, bizPeople);
            this.doIsCommittee(bizPeopleVo, bizPeople);
            this.doIsParty(bizPeopleVo, bizPeople);
            bizPeople.setIsHead(0L);
            if (BizUtils.cleanString(bizPeopleVo.getPeopleCard()).equals(BizUtils.cleanString(bizPeopleVo.getHeadPeopleCard()))) {
                //获取户主ID
                bizPeople.setIsHead(1L);
            }
            bizPeople.setStatus(1);
            bizPeople.setPeopleSex(IDCardUtil.getSex(BizUtils.cleanString(bizPeopleVo.getPeopleCard())));
            bizPeople.setPeopleBirth(IDCardUtil.getBirthday(BizUtils.cleanString(bizPeopleVo.getPeopleCard())));
            try {
                this.bizPeopleMapper.insertBizPeople(bizPeople);
                if (bizPeople.getIsHead().equals(1l)) {
                    BizFamily bizFamily = new BizFamily();
                    bizFamily.setCommunityId(bizPeople.getCommunityId());
                    bizFamily.setCommunityName(bizPeople.getCommunityName());
                    bizFamily.setFamilyHeadCard(BizUtils.cleanString(bizPeople.getHeadCard()));
                    bizFamily.setFamilyMobile(bizPeople.getPeopleMobile());
                    bizFamily.setFamilyName(bizPeople.getPeopleName());
                    bizFamily.setFamilyScore(0L);
                    bizFamily.setStatus("1");
                    bizFamily.setExpireStart(DateUtils.str2localDate(specialConfigValue.getStart()));
                    bizFamily.setExpireEnd(DateUtils.str2localDate(specialConfigValue.getEnd()));
                    familyService.insertBizFamily(bizFamily);
                }
                i++;
            } catch (Exception exception) {
                error.add(bizPeopleVo.getPeopleName());
                //throw new ServiceException("请补全数据再进行上传");
            }
        }
        if (error.size() > 0) {
            String exist = error.stream().map(String::valueOf).collect(Collectors.joining("\n"));
            throw new ServiceException(exist + ",请检查错误");
        }
        return "导入" + i + "村民信息";
    }

    private void doIsParty(BizPeopleVo bizPeopleVo, BizPeople bizPeople) {
        if ("1".equals(bizPeopleVo.getParty())) {
            bizPeople.setIsParty(1L);
        } else {
            bizPeople.setIsParty(0L);
        }
    }

    /**
     * 是否是居委
     *
     * @param bizPeopleVo
     * @param bizPeople
     */
    private void doIsCommittee(BizPeopleVo bizPeopleVo, BizPeople bizPeople) {
        if (Whether.YES.getTag().equals(bizPeopleVo.getIsCommittee())) {
            bizPeople.setIsCommittee(1L);
        }
    }

    /**
     * 是否是网格
     *
     * @param bizPeopleVo
     * @param bizPeople
     */
    private void doIsGrid(BizPeopleVo bizPeopleVo, BizPeople bizPeople) {
        if (Whether.YES.getTag().equals(bizPeopleVo.getGrid())) {
            bizPeople.setIsGrid(1L);
        }
    }

    /**
     * 设置网格
     *
     * @param bizGridsMap
     * @param bizPeopleVo
     * @param bizPeople
     */
    private void doGrids(Map<Long, List<BizGrid>> bizGridsMap, BizPeopleVo bizPeopleVo, BizPeople bizPeople) {
        if (StringUtils.isNotEmpty(bizPeopleVo.getGrid()) && bizGridsMap.containsKey(bizPeople.getCommunityId())) {
            List<BizGrid> bizGrids = bizGridsMap.get(bizPeople.getCommunityId());
            for (BizGrid bizGrid : bizGrids) {
                if (bizGrid.getGridName().equals(bizPeopleVo.getGrid())) {
                    bizPeople.setGridId(bizGrid.getGridId());
                    bizPeople.setGridName(bizGrid.getGridName());
                    break;
                }
            }

        }
    }

    /**
     * 获取社区ID
     *
     * @param communitiesMap
     * @param bizPeopleVo
     * @param bizPeople
     */
    private void doCommunity(Map<String, BizCommunity> communitiesMap, BizPeopleVo bizPeopleVo, BizPeople bizPeople) {

        if (communitiesMap.containsKey(bizPeopleVo.getCommunity())) {
            BizCommunity bizCommunity = communitiesMap.get(bizPeopleVo.getCommunity());
            bizPeople.setCommunityId(bizCommunity.getCommunityId());
            bizPeople.setCommunityName(bizCommunity.getCommunityName());
        }
    }

    /**
     * 表格存在空的判断
     *
     * @param bizPeopleVo
     * @param row
     */
    private void doEmpty(BizPeopleVo bizPeopleVo, int row) {
        if (StringUtils.isEmpty(bizPeopleVo.getPeopleName())) {
            throw new ServiceException("表格第" + row + "行,村居民->姓名空了");
        } else if (StringUtils.isEmpty(bizPeopleVo.getPeopleMobile())) {
            throw new ServiceException("表格第" + row + "行,村居民->手机号码空了");
        } else if (StringUtils.isEmpty(bizPeopleVo.getPeopleCard())) {
            throw new ServiceException("表格第" + row + "行,村居民->身份证空了");
        } else if (StringUtils.isEmpty(bizPeopleVo.getHeadPeopleCard())) {
            throw new ServiceException("表格第" + row + "行,户主身份证号->身份证空了");
        } else if (StringUtils.isEmpty(bizPeopleVo.getCommunity())) {
            throw new ServiceException("表格第" + row + "行,村民->所属村社空了");
        }
    }


    public static void main(String[] args) {
        Integer sex = IDCardUtil.getSex("342623198511116333");
        String birthday = IDCardUtil.getBirthday("342623198511116333");
        System.out.println("sex = " + sex);
        System.out.println("birthday = " + birthday);

        // 图片尺寸
        int width = 827;
        int height = 1240;
//        // 创建空白图片
//        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//        // 获取绘图对象
//        Graphics2D graphics2D = ImgUtil.createGraphics(bufferedImage, null);
//        // 设置渐变颜色（从左上到右下）
//        Color color1 = new Color(255, 255, 255); // 红色
//        Color color2 = new Color(0, 200, 255); // 蓝色
//        GradientPaint gradient = new GradientPaint(0, 0, color1, width, height, color2);
//        // 设置渐变填充
//        graphics2D.setPaint(gradient);
//        graphics2D.fill(new Rectangle2D.Double(0, 0, width, height));
        // 如果需要，这里可以添加更多图形操作，如绘制二维码等
        // 创建空白图片
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        // 获取绘图对象
        Graphics2D graphics2D = ImgUtil.createGraphics(bufferedImage, null);
        // 设置抗锯齿
        graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        BufferedImage bgImage = ImgUtil.read("E:\\project\\gaoting\\Gaoting.YzSite.AdminApi\\ruoyi-admin\\src\\main\\resources\\material\\bgall2.jpg");
        // 检查背景图片是否小于目标图片尺寸，如果是，则按比例缩放背景图片
        if (bgImage.getWidth() != width || bgImage.getHeight() != height) {
            double scale = Math.min((double) width / bgImage.getWidth(), (double) height / bgImage.getHeight());
            bgImage = bufferedImageResize(bgImage, (int) (bgImage.getWidth() * scale), (int) (bgImage.getHeight() * scale));
        }
        // 将背景图片绘制到目标图片上
        graphics2D.drawImage(bgImage, 0, 0, width, height, null);


        // 3. 在图片上添加中文文本，支持手动换行
        Font font = new Font("微软雅黑", Font.BOLD, 100); // 替换成所需的字体和大小
        Color textColor = Color.BLACK; // 文本颜色
        int textWidth = bufferedImage.getWidth() - 40; // 文本可用的宽度
        addTextToImage(bufferedImage, "桥 头 卡", font, textColor, textWidth, 200);


        // 图片尺寸
        // 你希望头像显示的直径大小
        int avatarSize = 300;
        // 创建一个与头像大小相同的透明缓冲区，用于绘制圆形头像
        BufferedImage circularAvatar = new BufferedImage(avatarSize, avatarSize, BufferedImage.TYPE_INT_ARGB);

        // 获取绘图对象
        Graphics2D headerG2d = ImgUtil.createGraphics(circularAvatar, null);
        // 设置抗锯齿
        headerG2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        // 绘制圆形头像
        // 设置剪裁为圆形
        headerG2d.setClip(new Ellipse2D.Double(0, 0, avatarSize, avatarSize));

        // 加载头像图片
        BufferedImage avatar = ImgUtil.read(URLUtil.url("https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132"));
        // 绘制头像
        headerG2d.drawImage(avatar, 0, 0, avatarSize, avatarSize, null);
        // 将圆形头像放置到渐变背景上
        graphics2D.drawImage(circularAvatar, (bufferedImage.getWidth() - avatarSize) / 2, 300, null);


        // 3. 在图片上添加中文文本，支持手动换行
        Font font1 = new Font("微软雅黑", Font.BOLD, 60);
        // 替换成所需的字体和大小
        addTextToImage(bufferedImage, "姓  名：" + "张三", font1, textColor, textWidth, 750);
        // 替换成所需的字体和大小
        addTextToImage(bufferedImage, "所在村：" + "安澜社区", font1, textColor, textWidth, 900);


        String content = "https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132";
        graphics2D.drawImage(generateQRCode(content, 350), (bufferedImage.getWidth() - 350) / 2, 1050, null);

        addTextToImage(bufferedImage, StrUtil.concat(true, "联系手机号码：", "130 0000 0000"), new Font("微软雅黑", Font.BOLD, 40), Color.WHITE, textWidth, 1500);

        // 关闭绘图上下文
        graphics2D.dispose();
        // 或者直接输出到Servlet响应
        // image.write(ServletActionContext.getResponse().getOutputStream());

        TiffImagingParameters params = new TiffImagingParameters();
        final PixelDensity pixelDensity = PixelDensity.createFromPixelsPerInch(300, 300);
        params.setPixelDensity(pixelDensity);
        TiffImageParser tiffImageParser = new TiffImageParser();
        try {
            tiffImageParser.writeImage(bufferedImage, new FileOutputStream(new File("D:\\test4444.tif")), params);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        ImgUtil.write(bufferedImage, new File("D:\\test.jpeg"));
        try {
            byte[] process = processDpi(bufferedImage, 300);
            FileUtil.writeBytes(process, "D:\\test12321.jpeg");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        ImageOutputStream out = null;
        try {
            out = ImgUtil.getImageOutputStream(new File("D:\\test2222.jpeg"));
            writeImageDpi(bufferedImage, ImgUtil.getWriter(bufferedImage, ImgUtil.IMAGE_TYPE_JPG), out, 300);
        } finally {
            IoUtil.close(out);
        }


    }

    /**
     * 设置图片DPI
     *
     * @param image
     * @param writer
     * @param output
     * @param dpi
     * @return
     */
    public static boolean writeImageDpi(BufferedImage image, ImageWriter writer, ImageOutputStream output, int dpi) {
        if (writer == null) {
            return false;
        }
        writer.setOutput(output);
        final RenderedImage renderedImage = ImgUtil.castToRenderedImage(image, ImgUtil.IMAGE_TYPE_JPG);
        try {
            if (dpi > 0) {
                ImageWriteParam param = writer.getDefaultWriteParam();
                IIOMetadata metadata1 = writer.getDefaultImageMetadata(new ImageTypeSpecifier(image.getColorModel(), image.getSampleModel()), param);
                Element tree = (Element) metadata1.getAsTree("javax_imageio_jpeg_image_1.0");
                Element jfif = (Element) tree.getElementsByTagName("app0JFIF").item(0);
                jfif.setAttribute("Xdensity", dpi + "");
                jfif.setAttribute("Ydensity", dpi + "");
                jfif.setAttribute("resUnits", "1");
                metadata1.mergeTree("javax_imageio_jpeg_image_1.0", tree);
                writer.write(null, new IIOImage(image, null, metadata1), param);
            } else {
                writer.write(renderedImage);
            }
            output.flush();
        } catch (IOException e) {
            throw new IORuntimeException(e);
        } finally {
            writer.dispose();
        }
        return true;
    }

    /**
     * 设置图片DPI
     *
     * @param image
     * @param dpi
     * @return
     * @throws IOException
     */
    public static byte[] processDpi(BufferedImage image, int dpi) throws IOException {
        for (Iterator<ImageWriter> iw = ImageIO.getImageWritersByFormatName("jpeg"); iw.hasNext(); ) {
            ImageWriter writer = iw.next();
            ImageWriteParam writeParams = writer.getDefaultWriteParam();
            writeParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            //调整图片质量
            writeParams.setCompressionQuality(1f);
            IIOMetadata data = writer.getDefaultImageMetadata(new ImageTypeSpecifier(image), writeParams);
            Element tree = (Element) data.getAsTree("javax_imageio_jpeg_image_1.0");
            Element jfif = (Element) tree.getElementsByTagName("app0JFIF").item(0);
            jfif.setAttribute("Xdensity", dpi + "");
            jfif.setAttribute("Ydensity", dpi + "");
            jfif.setAttribute("resUnits", "1");
            data.mergeTree("javax_imageio_jpeg_image_1.0", tree);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ImageOutputStream stream = null;
            try {
                stream = ImageIO.createImageOutputStream(out);
                writer.setOutput(stream);
                writer.write(null, new IIOImage(image, null, data), writeParams);
            } finally {
                if (ObjectUtil.isNotNull(stream)) {
                    stream.close();
                }
            }
            return out.toByteArray();
        }
        return null;
    }


    // 在图片上添加文本，支持手动换行，文本水平居中
    private static void addTextToImage(BufferedImage baseImage, String text, Font font, Color color, int maxWidth, int y) {
        Graphics2D g2d = baseImage.createGraphics();
        // 设置抗锯齿
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g2d.setFont(font);
        g2d.setColor(color);

        FontMetrics fm = g2d.getFontMetrics();
        int lineHeight = fm.getHeight();
        int currentY = y;
        String[] lines = text.split("\n");

        for (String line : lines) {
            int lineWidth = fm.stringWidth(line);
            // 居中
            int lineX = (maxWidth - lineWidth) / 2;
            g2d.drawString(line, lineX, currentY);
            currentY += lineHeight;
        }
        g2d.dispose();
    }

    // 生成二维码图片
    private static BufferedImage generateQRCode(String text, int size) {
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        try {
            QRCodeWriter writer = new QRCodeWriter();
            BitMatrix bitMatrix = writer.encode(text, BarcodeFormat.QR_CODE, size, size, hints);
            int width = bitMatrix.getWidth();
            int height = bitMatrix.getHeight();
            BufferedImage qrImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
            Graphics2D graphics = qrImage.createGraphics();
            graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            graphics.setColor(Color.WHITE);
            graphics.fillRect(0, 0, size, size);
            graphics.setColor(Color.BLACK);

            for (int x = 0; x < size; x++) {
                for (int y = 0; y < size; y++) {
                    if (bitMatrix.get(x, y)) {
                        graphics.fillRect(x, y, 1, 1);
                    }
                }
            }

            // 渲染二维码
            Graphics2D graphics1 = qrImage.createGraphics();
            graphics1.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            // 添加蓝色边框
            int borderSize = 10; // 边框大小
            Color myColor = new Color(0x19, 0x76, 0xFF); // 红色
            graphics1.setColor(myColor);
            graphics1.fillRect(0, 0, size, borderSize); // 上边框
            graphics1.fillRect(0, 0, borderSize, size); // 左边框
            graphics1.fillRect(size - borderSize, 0, borderSize, size); // 右边框
            graphics1.fillRect(0, size - borderSize, size, borderSize); // 下边框
            return qrImage;
        } catch (WriterException e) {
            e.printStackTrace();
            return null;
        }
    }

    // 生成二维码图片
    private static BufferedImage generateQRCode(byte[] bytes, int size) {
        BufferedImage qrImage = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB);
        Graphics2D graphics = qrImage.createGraphics();
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, size, size);
        graphics.setColor(Color.BLACK);
        graphics.drawImage(ImgUtil.read(new ByteArrayInputStream(bytes)), 0, 0, size, size, null);


        // 渲染二维码
        Graphics2D graphics1 = qrImage.createGraphics();
        graphics1.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        // 添加蓝色边框
        int borderSize = 10; // 边框大小
        Color myColor = new Color(255, 255, 255, 0); // 红色
        graphics1.setColor(myColor);
        graphics1.fillRect(0, 0, size, borderSize); // 上边框
        graphics1.fillRect(0, 0, borderSize, size); // 左边框
        graphics1.fillRect(size - borderSize, 0, borderSize, size); // 右边框
        graphics1.fillRect(0, size - borderSize, size, borderSize); // 下边框
        return qrImage;
    }

    @Resource
    private WxServiceProperties wxServiceProperties;

    /**
     * 生成成名身份牌
     *
     * @param response
     * @param peopleId
     */
    @Override
    public BizPeopleCard2Vo generatePeopleCard(HttpServletResponse response, Long peopleId) {
        BizPeople people = selectBizPeopleByPeopleId(peopleId);
        if (ObjectUtil.isNull(people)) {
            throw new ServiceException("村民信息不存在");
        }
        if (ObjectUtil.notEqual(NumberUtil.parseInt(people.getStatus().toString(), 0), 1)) {
            throw new ServiceException("村民信息审核未通过无法生成身份牌");
        }
        BizPeopleCard2Vo result = BeanUtil.toBean(people, BizPeopleCard2Vo.class);
        // 图片尺寸
        int width = 661;
        int height = 1016;
        // 创建空白图片
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        // 获取绘图对象
        Graphics2D graphics2D = ImgUtil.createGraphics(bufferedImage, null);// 设置抗锯齿
        graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        // this.getClass().getResourceAsStream("material/bgall2.jpg")
        BufferedImage bgImage = ImgUtil.read(ResourceUtil.getResource("material/bgall3.jpg"));
        // 检查背景图片是否小于目标图片尺寸，如果是，则按比例缩放背景图片
        if (bgImage.getWidth() != width || bgImage.getHeight() != height) {
            double scale = Math.min((double) width / bgImage.getWidth(), (double) height / bgImage.getHeight());
            bgImage = bufferedImageResize(bgImage, (int) (bgImage.getWidth() * scale), (int) (bgImage.getHeight() * scale));
        }
        // 将背景图片绘制到目标图片上
        graphics2D.drawImage(bgImage, 0, 0, width, height, null);
        // logo
//        BufferedImage headImage = ImgUtil.read(ResourceUtil.getResource("material/bz@3x.png"));
//        // 将背景图片绘制到目标图片上
//        graphics2D.drawImage(headImage, (bufferedImage.getWidth() - headImage.getWidth()) / 2, 80, null);

        // 如果需要，这里可以添加更多图形操作，如绘制二维码等
        Font font = FontUtil.createFont(ResourceUtil.getStreamSafe("font/STYuanti-SC-Regular.ttf"));
        // 文本颜色
        Color textColor = Color.BLACK;
        // 文本可用的宽度
        int textWidth = bufferedImage.getWidth() - 30;

        // 1. 名字
        addTextToImage(bufferedImage, people.getPeopleName(), font.deriveFont(Font.PLAIN, 60), textColor, bufferedImage.getWidth(), 480);

        // 3. 在图片上添加中文文本，支持手动换行
//        // 替换成所需的字体和大小
//        addTextToImage(bufferedImage, "姓  名：" + people.getPeopleName(), font1, textColor, textWidth, 750);
        // 所属社区名称
        String communityName = null;
        if (ObjectUtil.isNotNull(people.getCommunityId())) {
            BizCommunity bizCommunity = bizCommunityService.selectBizCommunityByCommunityId(people.getCommunityId());
            if (ObjectUtil.isNotNull(bizCommunity)) {
                communityName = bizCommunity.getCommunityName();
            }
        }
        addTextToImage(bufferedImage, StrUtil.concat(true, "所在村社：", communityName), font.deriveFont(Font.PLAIN, 35), textColor, bufferedImage.getWidth(), 550);
//        addTextToImage(bufferedImage, StrUtil.concat(true, "电  话：", people.getPeopleMobile()), font.deriveFont(Font.PLAIN, 40), textColor, textWidth, 770);
        try {
//            String proxyPage = sysConfigService.selectConfigByKey(Constants.WX_MP_PROXY_LOGIN_PAGE);
//            if (StrUtil.isNotBlank(proxyPage)) {
//                proxyPage = ("?a=" + peopleId + "&b=" + people.getPeopleCard());
//            }
//            graphics2D.drawImage(generateQRCode(proxyPage, 350), (bufferedImage.getWidth() - 350) / 2, 1100, null);
            SchemaQrCodeVo schemaQrCodeVo = new SchemaQrCodeVo();
            schemaQrCodeVo.setPagePath(Constants.WX_MP_PAGE_SCAN_PATH);
            schemaQrCodeVo.setScene("a=1&q=" + peopleId);
            schemaQrCodeVo.setEnvVersion(sysConfigService.selectConfigByKey(Constants.WX_MP_ENV_VERSION));
            String post = HttpUtil.post(wxServiceProperties.getHostPath() + wxServiceProperties.getApiSuffix().getSchemaQrCode(), JSONUtil.toJsonStr(schemaQrCodeVo), 60000);
            byte[] data = JSONUtil.parseObj(post).get("data", byte[].class);
            if (ObjectUtil.isNull(data)) {
                throw new ServiceException("获取微信二维码失败");
            }
            graphics2D.drawImage(generateQRCode(data, 350), (bufferedImage.getWidth() - 350) / 2, 600, null);
        } catch (Exception e) {
            log.error("generatePeopleCard 生成小程序码失败：", e);
            throw new ServiceException("获取微信二维码失败");
        }
        // 关闭绘图上下文
        graphics2D.dispose();
        try {
            // 设置dpi
            byte[] process = processDpi(bufferedImage, 300);
            result.setPeopleIdCardImg(process);
            if (ObjectUtil.isNotNull(response)) {
                response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
                FileUtils.setAttachmentResponseHeader(response, IdUtil.fastSimpleUUID() + "." + ImgUtil.IMAGE_TYPE_JPEG);
                response.getOutputStream().write(process);
            }
//            ImgUtil.write(bufferedImage, ImgUtil.IMAGE_TYPE_JPEG, response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException("下载身份牌失败");
        }
        return result;
    }

    private static BufferedImage bufferedImageResize(BufferedImage bgImage, int width, int height) {
        //图片缩放
        BufferedImage updateImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        // 获取 Graphics2D 对象
        Graphics2D g2d = updateImage.createGraphics();
        // 设置抗锯齿
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        // 清除背景，使其完全透明
        g2d.setComposite(AlphaComposite.Clear);
        g2d.fillRect(0, 0, width, height);
        g2d.setComposite(AlphaComposite.SrcOver);
        //放大图片
        g2d.drawImage(bgImage, 0, 0, width, height, null);
        return updateImage;
    }

    /**
     * 根据户主身份证查看家庭成员
     *
     * @param familyPeople
     * @return
     */
    @Override
    public List<BizPeople> familyPeople(FamilyPeople familyPeople) {
        BizPeople current = this.selectBizPeopleByPeopleId(familyPeople.getPeopleId());
        BizPeople bizPeople = new BizPeople();
        bizPeople.setHeadCard(current.getHeadCard());
        List<BizPeople> peopleList = this.bizPeopleMapper.familyPeople(bizPeople);
        return peopleList;
    }

    @Override
    public BoardViewVo systemBoardView() {
        BoardViewVo boardViewVo = new BoardViewVo();
        //-----------------------已审核的正常数据---------------------
        BoardViewVo.InnerNormalView innerNormalView = new BoardViewVo.InnerNormalView();
        //已审核的村民
        long audited = bizPeopleMapper.selectBizPeopleByStatus(1);
        //网格员总数
        Long isGridTotal = bizPeopleMapper.selectIsGrids();
        //商家总数
        long sellerTotal = bizSellerService.selectBizSellerByAudit(1);

        //网格数
        long gridTotal = gridService.selectBizGridTotal();
        innerNormalView.setAuditedTotal(audited);
        innerNormalView.setIsGridTotal(isGridTotal);
        innerNormalView.setGridTotal(gridTotal);
        innerNormalView.setSellerTotal(sellerTotal);
        boardViewVo.setNormalView(innerNormalView);
        //-----------------------已审核的正常数据---------------------
        long couponTotal = bizCouponService.selectBizCouponByAudit(1);
        //----------------------待审核的数据----------------
        //待审核的商家总数
        long waitingAuditedSellerTotal = bizSellerService.selectBizSellerByAudit(0);
        //待审核的村民
        long waitingAudited = bizPeopleMapper.selectBizPeopleByStatus(0);
        long peopleGoodsTotal = bizPeopleGoodsService.selectBizPeopleGoodsByStatus(0);
        BoardViewVo.InnerAuditView innerAuditView = new BoardViewVo.InnerAuditView();
        //待审核的村民
        innerAuditView.setPeopleTotal(waitingAudited);
        //待审核的商家
        innerAuditView.setSellerTotal(waitingAuditedSellerTotal);
        //待审核的券
        innerAuditView.setCouponTotal(couponTotal);
        //待兑换的商品
        innerAuditView.setPeopleGoodsTotal(peopleGoodsTotal);
        boardViewVo.setAuditView(innerAuditView);
        //----------------------积分---------------------
        BoardViewVo.InnerScoreView innerScoreView = new BoardViewVo.InnerScoreView();
        Long total = bizFamilyScoreLogService.sendTotal(1, null, null);
        Long usedTotal = bizFamilyScoreLogService.sendTotal(2, null, null);
        //今日发放积分  今日消耗消耗
        Long todaySendTotal = bizFamilyScoreLogService.sendTotal(1, DateUtils.start(), DateUtils.end());
        Long todayUsedTotal = bizFamilyScoreLogService.sendTotal(2, DateUtils.start(), DateUtils.end());
        innerScoreView.setTotal(total);
        innerScoreView.setUsedTotal(usedTotal);
        innerScoreView.setTodaySendTotal(todaySendTotal);
        innerScoreView.setTodayUsedTotal(todayUsedTotal);
        boardViewVo.setScoreView(innerScoreView);
        //----------------------积分---------------------
        //----------------------商家券数据---------------------
        BoardViewVo.InnerCouponView innerCouponView = new BoardViewVo.InnerCouponView();
        //----------------------商家券数据---------------------
        // bizCouponService
        // bizPeopleCouponService
        //创建券总数
        BizCoupon sellerCouponTotalVo = new BizCoupon();
        sellerCouponTotalVo.setStatus("0");
        Long sellerCouponTotal = bizCouponService.selectBizCouponTotal(sellerCouponTotalVo);
        innerCouponView.setTotal(sellerCouponTotal);
        //待使用
        BizCoupon readyUsedTotalVo = new BizCoupon();
        readyUsedTotalVo.setStatus("0");
        readyUsedTotalVo.setStartTime(DateUtils.start());
        readyUsedTotalVo.setEndTime(DateUtils.end());
        Long readyUsedTotal = bizPeopleCouponService.selectTotalByStatus(readyUsedTotalVo);
        //已经使用
        BizCoupon alreadyTotalVo = new BizCoupon();
        readyUsedTotalVo.setStatus("1");
        Long alreadyTotal = bizPeopleCouponService.selectTotalByStatus(alreadyTotalVo);

        BizCoupon expiredTotalVo = new BizCoupon();
        readyUsedTotalVo.setStatus("0");
        readyUsedTotalVo.setEndTime(LocalDateTime.now());
        Long expiredTotal = bizPeopleCouponService.expiredTotal(expiredTotalVo);
        innerCouponView.setUsedTotal(readyUsedTotal);
        innerCouponView.setExpiredTotal(expiredTotal);
        innerCouponView.setAlreadyTotal(alreadyTotal);
        boardViewVo.setCouponView(innerCouponView);
        //----------------------商家券数据---------------------

        return boardViewVo;
    }

    @Override
    public List<FamilyScoreLogViewVo> getScoreLogGroupByDay(String startDate, String endDate) {
        if (StrUtil.isAllBlank(startDate, endDate)) {
            DateTime dateTime = DateUtil.date();
            endDate = dateTime.toDateStr();
            startDate = dateTime.offset(DateField.DAY_OF_YEAR, -7).toDateStr();
        }
        if (StrUtil.isBlank(startDate)) {
            startDate = DateUtil.parse(endDate).offset(DateField.DAY_OF_YEAR, -7).toDateStr();
        }
        if (StrUtil.isBlank(endDate)) {
            endDate = DateUtil.parse(startDate).offset(DateField.DAY_OF_YEAR, 7).toDateStr();
        }
        List<DateTime> dateTimes = DateUtil.rangeToList(DateUtil.parse(startDate), DateUtil.parse(endDate), DateField.DAY_OF_YEAR);
        List<FamilyScoreLogViewVo> scoreLogGroupByDay = bizPeopleMapper.getScoreLogGroupByDay(startDate, endDate);
        Map<String, FamilyScoreLogViewVo> logViewVoMap = CollUtil.isNotEmpty(scoreLogGroupByDay) ? scoreLogGroupByDay.stream().collect(Collectors.toMap(FamilyScoreLogViewVo::getCreateDay, a -> a)) : new HashMap<>();
        List<FamilyScoreLogViewVo> familyScoreLogViewVos = new ArrayList<>();
        dateTimes.forEach(date -> {
            FamilyScoreLogViewVo familyScoreLogViewVo = MapUtil.get(logViewVoMap, date.toDateStr(), FamilyScoreLogViewVo.class, new FamilyScoreLogViewVo());
            familyScoreLogViewVo.setCreateDay(date.toDateStr());
            familyScoreLogViewVos.add(familyScoreLogViewVo);
        });
        return familyScoreLogViewVos;
    }

    /**
     * 审核居民信息
     *
     * @param bizPeople
     * @return
     */
    @Override
    public int auditPeople(BizPeople bizPeople) {
        BizPeople find = this.bizPeopleMapper.selectBizPeopleByPeopleId(bizPeople.getPeopleId());
        if (ObjectUtil.isNull(find)) {
            throw new ServiceException("该居民不存在");
        }
        if (find.getStatus().equals(1)) {
            throw new ServiceException("该居民已经审核了");
        }

        List<BirdsTree> birdsTrees = gridService.getGridListBy(find.getCommunityId());
        BirdsTree.InnerGrid innerGrid = birdsTrees.get(0).getChildren().get(0);
        //检查当前用户是否开通了家庭积分
        if (StrUtil.isBlank(find.getHeadCard())) {
            ExtraConfig specialConfigValue = sysConfigService.getSpecialConfigValue();
            BizFamily bizFamily = new BizFamily();
            bizFamily.setCommunityId(find.getCommunityId());
            bizFamily.setCommunityName(find.getCommunityName());
            bizFamily.setFamilyHeadCard(find.getPeopleCard());
            bizFamily.setFamilyName(find.getPeopleName());
            bizFamily.setFamilyMobile(find.getPeopleMobile());
            bizFamily.setFamilyScore(0L);
            bizFamily.setStatus("1");
            if (find.getPeopleCard().equals(find.getHeadCard())) {
                find.setIsHead(1l);
            }
            bizFamily.setExpireStart(DateUtils.str2localDate(specialConfigValue.getStart()));
            bizFamily.setExpireEnd(DateUtils.str2localDate(specialConfigValue.getEnd()));
            familyService.insertBizFamily(bizFamily);
            //throw new ServiceException("该居民还没有设置归属户主");
        }
        find.setGridId(innerGrid.getId());
        find.setGridName(innerGrid.getLabel());
        find.setHeadCard(find.getPeopleCard());
        find.setStatus(1);
        find.setIsHead(1L);
        find.setUpdateBy(SecurityUtils.getUsername());
        find.setUpdateTime(DateUtil.date());
        return this.bizPeopleMapper.updateBizPeople(find);
    }

    @Override
    public int setHeadCard(BizPeople bizPeople) {
        BizPeople find = this.bizPeopleMapper.selectBizPeopleByPeopleId(bizPeople.getPeopleId());
        if (ObjectUtil.isNull(find)) {
            throw new ServiceException("该居民不存在");
        }
        if (StrUtil.isNotBlank(find.getHeadCard())) {
            throw new ServiceException("该居民已经有归属户主了");
        }
        find.setHeadCard(find.getPeopleCard());
        find.setIsHead(1L);
        find.setUpdateTime(DateUtil.date());
        find.setUpdateBy(SecurityUtils.getUsername());
        //开头家庭用户
        ExtraConfig specialConfigValue = sysConfigService.getSpecialConfigValue();
        BizFamily bizFamily = new BizFamily();
        bizFamily.setCommunityId(find.getCommunityId());
        bizFamily.setCommunityName(find.getCommunityName());
        bizFamily.setFamilyHeadCard(find.getPeopleCard());
        bizFamily.setFamilyName(find.getPeopleName());
        bizFamily.setFamilyMobile(find.getPeopleMobile());
        bizFamily.setFamilyScore(0L);
        bizFamily.setCreateBy(SecurityUtils.getUsername());
        bizFamily.setUpdateBy(SecurityUtils.getUsername());
        bizFamily.setCreateTime(DateUtils.getNowDate());
        bizFamily.setUpdateTime(DateUtils.getNowDate());
        bizFamily.setExpireStart(DateUtils.str2localDate(specialConfigValue.getStart()));
        bizFamily.setExpireEnd(DateUtils.str2localDate(specialConfigValue.getEnd()));
        familyService.insertBizFamily(bizFamily);
        return this.bizPeopleMapper.updateBizPeople(find);
    }

    /**
     * 设置网格员
     *
     * @param girdVo
     * @return
     */
    @Override
    public int setGird(GirdVo girdVo) {

        //取消深圳
        if (GirdSetting.NO.getCode().equals(girdVo.getIsSetting())) {
            BizPeople bizPeople = new BizPeople();
            bizPeople.setIsGrid(0l);
            bizPeople.setPeopleId(girdVo.getPeopleId());
            bizPeople.setUpdateBy(SecurityUtils.getUsername());
            bizPeople.setUpdateTime(DateUtil.date());
            //删除网格
            gridMappingService.deleteBizGridMappingByPeopleId(girdVo.getPeopleId());
            return this.bizPeopleMapper.updateBizPeople(bizPeople);
        } else if (GirdSetting.YES.getCode().equals(girdVo.getIsSetting())) {
            BizPeople bizPeople = new BizPeople();
            bizPeople.setIsGrid(1l);
            bizPeople.setPeopleId(girdVo.getPeopleId());
            bizPeople.setUpdateBy(SecurityUtils.getUsername());
            bizPeople.setUpdateTime(DateUtil.date());
            //删除网格
            gridMappingService.deleteBizGridMappingByPeopleId(girdVo.getPeopleId());
            for (GirdVo.InnerGirds gird : girdVo.getGirds()) {
                BizGridMapping bizGridMapping = new BizGridMapping();
                bizGridMapping.setGridId(gird.getId());
                bizGridMapping.setGridName(gird.getLabel());
                bizGridMapping.setPeopleId(girdVo.getPeopleId());
                bizGridMapping.setCommunityId(girdVo.getCommunityId());
                bizGridMapping.setCommunityName(girdVo.getCommunityName());
                bizGridMapping.setCreateBy(SecurityUtils.getUsername());
                bizGridMapping.setCreateTime(DateUtil.date());
                gridMappingService.insertBizGridMapping(bizGridMapping);
            }
            return this.bizPeopleMapper.updateBizPeople(bizPeople);
        } else {
            throw new ServiceException("设置网格员条件异常");
        }
    }

    @Override
    public int resetPeopleOpenId(List<Long> peopleIds) {
        return this.bizPeopleMapper.resetPeopleOpenId(peopleIds);
    }

    /**
     * 重置微信
     *网格员 离职 还用旧的手机号
     * @param bizPeople
     * @return
     */
    @Override
    public int resetWx(BizPeople bizPeople,String opName) {

        BizPeople one = this.bizPeopleMapper.findByPeopleCard(bizPeople.getPeopleCard());
        if (Objects.nonNull(one)) {
            throw new ServiceException("绑定的身份证号已经存在");
        }
        BizPeople newPeople = new BizPeople();
        newPeople.setPeopleName(bizPeople.getPeopleName());
        newPeople.setPeopleCard(bizPeople.getPeopleCard());
        newPeople.setHeadCard(bizPeople.getPeopleCard());
        newPeople.setIsHead(1l);
        newPeople.setOpenId("");
        newPeople.setPeopleId(bizPeople.getPeopleId());
        newPeople.setUpdateTime(DateUtils.getNowDate());
        newPeople.setUpdateBy(opName);


        ExtraConfig specialConfigValue = sysConfigService.getSpecialConfigValue();
        BizFamily bizFamily = new BizFamily();
        bizFamily.setCommunityId(bizPeople.getCommunityId());
        bizFamily.setCommunityName(bizPeople.getCommunityName());
        bizFamily.setFamilyHeadCard(bizPeople.getPeopleCard());
        bizFamily.setFamilyName(bizPeople.getPeopleName());
        bizFamily.setFamilyMobile(bizPeople.getPeopleMobile());
        bizFamily.setFamilyScore(0L);
        bizFamily.setCreateBy(opName);
        bizFamily.setUpdateBy(opName);
        bizFamily.setCreateTime(DateUtils.getNowDate());
        bizFamily.setUpdateTime(DateUtils.getNowDate());
        bizFamily.setExpireStart(DateUtils.str2localDate(specialConfigValue.getStart()));
        bizFamily.setExpireEnd(DateUtils.str2localDate(specialConfigValue.getEnd()));
        familyService.insertBizFamily(bizFamily);
        return this.bizPeopleMapper.resetWx(newPeople);
    }

    /**
     * 通过成员名称寻找户主
     *
     * @param peopleName
     * @return
     */
    @Override
    public BizPeople selectBizPeopleByPeopleName(String peopleName) {
        return this.bizPeopleMapper.selectBizPeopleByPeopleName(peopleName);
    }

    /**
     * 变更社区
     *
     * @param bizSetCommunity
     * @param username
     * @return
     */
    @Override
    public int doSetCommunity(BizSetCommunity bizSetCommunity, String username) {
        BizCommunity bizCommunity = bizCommunityService.selectBizCommunityByCommunityId(bizSetCommunity.getCommunityId());
        BizGrid bizGrid = gridService.selectBizGridByGridId(bizSetCommunity.getGridId());
        if (Objects.isNull(bizCommunity)) {
            throw new ServiceException("社区不存在");
        }
        if (Objects.isNull(bizGrid) || !bizGrid.getCommunityId().equals(bizSetCommunity.getCommunityId())) {
            throw new ServiceException("网格不存在");
        }
        ExtraConfig specialConfigValue = sysConfigService.getSpecialConfigValue();

        BizPeople bizPeople = this.bizPeopleMapper.selectBizPeopleByPeopleId(bizSetCommunity.getPeopleId());
        if (Objects.isNull(bizPeople)) {
            throw new ServiceException("用户不存在");
        }
        if(bizPeople.getCommunityId().equals(bizSetCommunity.getCommunityId())) {
            throw new ServiceException("用户社区无变化");
        }
        //变更用户的社区
        BizPeople newBizPeople = new BizPeople();
        newBizPeople.setPeopleId(bizSetCommunity.getPeopleId());
        newBizPeople.setCommunityId(bizSetCommunity.getCommunityId());
        newBizPeople.setCommunityName(bizCommunity.getCommunityName());
        newBizPeople.setGridId(bizSetCommunity.getGridId());
        newBizPeople.setGridName(bizGrid.getGridName());
        newBizPeople.setUpdateBy(username);
        newBizPeople.setUpdateTime(DateUtils.getNowDate());

        // 户主单独一户，随机选取一位家庭成员成户主
        if (bizPeople.getIsHead().equals(1l)) {

            List<BizPeople> noHeads = bizPeopleMapper.selectPeopleNotHead(bizPeople.getHeadCard());
            //说明没有家庭成员
            if (Objects.nonNull(noHeads) && noHeads.size()>0) {
                int i = 0;
                BizPeople currentHeadPeople = null;
                for (BizPeople noHead : noHeads) {
                    // 将当前用户设为户主
                    if (i==0) {
                        noHead.setIsHead(1l);
                        currentHeadPeople = noHead;
                    }
                    noHead.setHeadCard(noHead.getPeopleCard());
                    noHead.setUpdateBy(username);
                    noHead.setUpdateTime(DateUtils.getNowDate());
                    this.bizPeopleMapper.updateBizPeople(noHead);
                    i++;
                }
                //更新家庭户主
                bizFamilyServiceImpl.updateBizFamilyByHeadCard(currentHeadPeople.getHeadCard()
                        ,bizPeople.getHeadCard()
                        ,currentHeadPeople.getPeopleName()
                        ,currentHeadPeople.getPeopleMobile()
                );
                //开通家庭积分
                BizFamily bizFamily = new BizFamily();
                bizFamily.setCommunityId(newBizPeople.getCommunityId());
                bizFamily.setCommunityName(newBizPeople.getCommunityName());
                bizFamily.setFamilyHeadCard(BizUtils.cleanString(bizPeople.getHeadCard()));
                bizFamily.setFamilyMobile(bizPeople.getPeopleMobile());
                bizFamily.setFamilyName(bizPeople.getPeopleName());
                bizFamily.setFamilyScore(0L);
                bizFamily.setStatus("1");
                bizFamily.setExpireStart(DateUtils.str2localDate(specialConfigValue.getStart()));
                bizFamily.setExpireEnd(DateUtils.str2localDate(specialConfigValue.getEnd()));
                familyService.insertBizFamily(bizFamily);
            }
        }
        //非户主 单独一户
        else {
            //设置当前用户非户主
            newBizPeople.setIsHead(1l);
            newBizPeople.setHeadCard(bizPeople.getPeopleCard());
            //开通家庭积分
            BizFamily bizFamily = new BizFamily();
            bizFamily.setCommunityId(newBizPeople.getCommunityId());
            bizFamily.setCommunityName(newBizPeople.getCommunityName());
            bizFamily.setFamilyHeadCard(BizUtils.cleanString(bizPeople.getPeopleCard()));
            bizFamily.setFamilyMobile(bizPeople.getPeopleMobile());
            bizFamily.setFamilyName(bizPeople.getPeopleName());
            bizFamily.setFamilyScore(0L);
            bizFamily.setStatus("1");
            bizFamily.setExpireStart(DateUtils.str2localDate(specialConfigValue.getStart()));
            bizFamily.setExpireEnd(DateUtils.str2localDate(specialConfigValue.getEnd()));
            familyService.insertBizFamily(bizFamily);
        }
        return  this.bizPeopleMapper.updateBizPeople(newBizPeople);
    }

    /**
     * 根据成员查看家庭
     *
     * @param peopleId
     * @return
     */
    @Override
    public FamilyDto findFamlily(Long peopleId) {
        BizPeople bizPeople = this.bizPeopleMapper.selectBizPeopleByPeopleId(peopleId);
        FamilyDto familyDto = new FamilyDto();
        if (Objects.isNull(bizPeople)) {
            familyDto.setHeaderPeople("");
            familyDto.setFamily("");
            return familyDto;
        }
        List<BizPeople> family = this.bizPeopleMapper.selectPeopleHead(bizPeople.getHeadCard());
        List<String> member= new ArrayList<>();
        for (BizPeople people : family) {

            if (people.getIsHead().equals(1l)) {
                familyDto.setHeaderPeople(people.getPeopleName());
            }
            else {
                member.add(people.getPeopleName());
            }
        }
        if (member.size()>0) {
            familyDto.setFamily(String.join(",",member));
        }
        else {
            familyDto.setFamily(familyDto.getHeaderPeople());
        }
        return familyDto;
    }

    /**
     * 普通村居民解绑微信号
     *
     * @param bizPeople
     * @param username
     * @return
     */
    @Override
    public int resetCommonWx(BizPeople bizPeople, String username) {
        BizPeople one = this.bizPeopleMapper.selectBizPeopleByPeopleId(bizPeople.getPeopleId());
        if (Objects.isNull(one)) {
            throw new ServiceException("要解绑的村居民不存在");
        }
        one.setOpenId("");
        one.setUpdateTime(DateUtils.getNowDate());
        one.setUpdateBy(username);
        return this.bizPeopleMapper.updateBizPeople(one);
    }
}
